package org.bootlimn.preprocessor;

import java.util.List;
import java.util.ArrayList;

import org.bootlimn.common.Process;
import org.bootlimn.common.TreeNode;

public class ProcTreeGenerator {
	
	private List<TreeNode> tree;
	private int level[];
	List<Process> listTree;
	
	public ProcTreeGenerator() {
		TreeNode dummy = new TreeNode();
		this.tree = new ArrayList<TreeNode>();
		this.tree.add(dummy);
		this.listTree = new ArrayList<Process>();
	}
		
	public List<Process> getUniqueProcesses(List<Process> processes) {
		List<Process> uniqueP = new ArrayList<Process>();
		int nP = processes.size();
		boolean pFlag = true;
		Process item = new Process();
		for (int k=0; k<nP; k++) {
			pFlag = true;
		    item = processes.get(k);
			for (int j=0; j<uniqueP.size(); j++) {
				Process temp = uniqueP.get(j);
				if(temp.getExecname().equals(item.getExecname()) && temp.getPid() == item.getPid() && temp.getPpid() == item.getPpid())  {
				pFlag = false;
				break;
				}
			}
		}
			
		if (pFlag == true) {
			uniqueP.add(item);
		}
		
	return uniqueP;
	}
	
	public void generateTree(List<Process> uniquePro) 
	{
		int num = uniquePro.size();
		for (int i =0; i<num; i++) 
		{
			boolean check = true;
			Process cur = uniquePro.get(i);
			TreeNode newnode = new TreeNode(cur);
			for(int j =0; j<this.tree.size(); j++) {
				TreeNode tmp = this.tree.get(j);
				if ((tmp.getParent()!= null) && (tmp.getParent().equals(newnode)))
				{
					tmp.addChild(newnode);
					this.tree.set(j,tmp);
					check = false;
					break;
				}
			}
			if( check)
			{
				TreeNode a = this.tree.get(0);
				a.addChild(newnode);
				this.tree.set(0, a);
			}
			
		}
	}
	
	public void recursiveAddToList(TreeNode tmp)
	{ 	
		if(tmp.getVal()!= null)
			{
				this.listTree.add(tmp.getVal());
				this.level[this.listTree.indexOf(tmp.getVal())] = tmp.getlevel();
			}
			if(tmp.getChildList().size() > 0)
			{
				List<TreeNode> x = tmp.getChildList();
				for (int i=0;i<x.size();i++)
				{ 
					if(x.get(i)!=null)
					{
						recursiveAddToList(x.get(i));
					}
				}
			}
		
	}
	
	public void convertTreeToList()
	{
		
		this.level = new int[tree.size()];
		recursiveAddToList(tree.get(0));
	}
	
	public List<Process>getlistTree()
	{
		return this.listTree;
	}
		
	public int[] getLevel()
	{
		return this.level;
	}
}